package com.cskaoyan.service.wx;

import com.cskaoyan.bean.*;
import com.cskaoyan.mapper.MarketCartMapper;
import com.cskaoyan.mapper.MarketCouponMapper;
import com.cskaoyan.mapper.MarketCouponUserMapper;
import com.cskaoyan.mapper.MarketOrderMapper;
import com.cskaoyan.model.vx.bo.WxCouponMyListBo;
import com.cskaoyan.model.vx.vo.WxCouponListVo;
import com.cskaoyan.model.vx.vo.WxCouponMyListVo;
import com.cskaoyan.model.vx.vo.WxCouponSelectListVo;
import com.github.pagehelper.PageHelper;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class WxCouponServiceImpl implements WxCouponService {
    @Autowired
    MarketCouponMapper marketCouponMapper;
    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;


    @Override
    public WxCouponMyListVo mylist(WxCouponMyListBo wxCouponMyListBo, Integer userId) {

        //更新过期的couponUser
        if (userId == null) {
            return null;
        }
        updateCouponUserExpired(userId);


        PageHelper.startPage(wxCouponMyListBo.getPage(), wxCouponMyListBo.getLimit());//查询前分页
        WxCouponMyListVo wxCouponMyListVo = new WxCouponMyListVo();
        MarketCouponUserExample marketCouponUserExample = new MarketCouponUserExample();
        MarketCouponUserExample.Criteria criteria = marketCouponUserExample.createCriteria();
        criteria.andStatusEqualTo((short) wxCouponMyListBo.getStatus());

        criteria.andUserIdEqualTo((Integer) userId);//通过用户Id,拿到用户所有优惠券的信息，遍历优惠券，将其赋值到list集合。
        List<MarketCouponUser> marketCouponUserList = marketCouponUserMapper.selectByExample(marketCouponUserExample);
        ArrayList<WxCouponMyListVo.ListEntity> listEntities = new ArrayList<>();//创建一个存放指定类型的list。
        for (MarketCouponUser coupon : marketCouponUserList) {
            MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(coupon.getCouponId());//通过user信息里的couponId,取数据。
            WxCouponMyListVo.ListEntity listEntity = new WxCouponMyListVo.ListEntity();
            listEntity.setAvailable(false);//
            listEntity.setCid(marketCoupon.getId());//优惠券ID
            listEntity.setDesc(marketCoupon.getDesc());
            listEntity.setDiscount(marketCoupon.getDiscount());
            listEntity.setEndTime(coupon.getEndTime());
            listEntity.setId(coupon.getUserId());//用户ID
            listEntity.setMin(marketCoupon.getMin());
            listEntity.setName(marketCoupon.getName());
            listEntity.setStartTime(coupon.getStartTime());
            listEntity.setTag(marketCoupon.getTag());


            wxCouponMyListVo.setList(listEntities);//将外部类的成员变量赋值，赋上我们创建的list对象
            listEntities.add(listEntity);//给list添加对象。
        }
        wxCouponMyListVo.setLimit(wxCouponMyListBo.getLimit());
        wxCouponMyListVo.setPage(wxCouponMyListBo.getPage());
        wxCouponMyListVo.setPages((marketCouponUserList.size() / 11) + 1);
        wxCouponMyListVo.setTotal(marketCouponUserList.size());
        return wxCouponMyListVo;
    }

    /**
     * 根据userId更新couponUser中过期的coupon
     */
    private void updateCouponUserExpired(Integer userId) {
        MarketCouponUserExample marketCouponUserExample = new MarketCouponUserExample();
        marketCouponUserExample.createCriteria().andUserIdEqualTo(userId).
                andEndTimeLessThan(new Date());
        MarketCouponUser record = new MarketCouponUser();
        record.setStatus((short) 2);
        marketCouponUserMapper.updateByExampleSelective(record, marketCouponUserExample);
    }

    /**
     * 更新coupon中过期的coupon
     */
    private void updateCouponExpired() {
        MarketCouponExample marketCouponExample = new MarketCouponExample();
        marketCouponExample.createCriteria().andEndTimeLessThan(new Date());
        MarketCoupon record = new MarketCoupon();
        record.setStatus((short) 1);
        marketCouponMapper.updateByExampleSelective(record, marketCouponExample);
    }


    @Override
    public WxCouponListVo list(WxCouponMyListBo wxCouponMyListBo) {

        //更新coupon过期
        updateCouponExpired();
        PageHelper.startPage(wxCouponMyListBo.getPage(), wxCouponMyListBo.getLimit());
        WxCouponListVo wxCouponListVo = new WxCouponListVo();
        ArrayList<WxCouponListVo.ListEntity> listEntities = new ArrayList<>();
        MarketCouponExample marketCouponExample = new MarketCouponExample();
        marketCouponExample.createCriteria().andStatusEqualTo((short)0);
        List<MarketCoupon> marketCoupons = marketCouponMapper.selectByExample(marketCouponExample);
        for (MarketCoupon marketCoupon : marketCoupons) {
            WxCouponListVo.ListEntity listEntity = new WxCouponListVo.ListEntity();
            listEntity.setDays(marketCoupon.getDays());
            listEntity.setDesc(marketCoupon.getDesc());
            listEntity.setDiscount(marketCoupon.getDiscount());
            listEntity.setId(marketCoupon.getId());
            listEntity.setMin(marketCoupon.getMin());
            listEntity.setName(marketCoupon.getName());
            listEntity.setTag(marketCoupon.getTag());

            listEntities.add(listEntity);
            wxCouponListVo.setList(listEntities);
        }
        wxCouponListVo.setLimit(wxCouponMyListBo.getLimit());
        wxCouponListVo.setPage(wxCouponMyListBo.getPage());
        wxCouponListVo.setPages((wxCouponMyListBo.getLimit() / 10) + 1);
        wxCouponListVo.setTotal(marketCoupons.size());

        return wxCouponListVo;
    }

    @Override
    public Integer receive(Integer couponId, Integer userId) {
        //首先拿到coupon
        MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(couponId);

        //判断是否以领取
        MarketCouponUserExample marketCouponUserExample = new MarketCouponUserExample();
        marketCouponUserExample.createCriteria().andCouponIdEqualTo(couponId);
        long affectedRows = marketCouponUserMapper.countByExample(marketCouponUserExample);
        if (affectedRows != 0) {
            return -1;
        }


        //将marketCoupon转换为marketCouponUser
        MarketCouponUser marketCouponUser = new MarketCouponUser();
        marketCouponUser.setUserId(userId);
        marketCouponUser.setCouponId(marketCoupon.getId());
        marketCouponUser.setStartTime(marketCoupon.getStartTime());
        marketCouponUser.setUpdateTime(new Date());
        marketCouponUser.setAddTime(new Date());
        marketCouponUser.setEndTime(marketCoupon.getEndTime());
        marketCouponUser.setStatus((short) 0);


        //插入couponUser
        marketCouponUserMapper.insertSelective(marketCouponUser);

        return 1;
    }

    @Override
    public Integer exchange(Integer userId, String code) {
        //筛入条件就是兑换码相等。
        MarketCouponExample marketCouponExample = new MarketCouponExample();
        MarketCouponExample.Criteria criteria = marketCouponExample.createCriteria();
        criteria.andCodeEqualTo(code);
        MarketCouponUserExample marketCouponUserExample = new MarketCouponUserExample();
        MarketCouponUserExample.Criteria criteria1 = marketCouponUserExample.createCriteria();
        Integer row = -1;
        List<MarketCoupon> marketCoupons = marketCouponMapper.selectByExample(marketCouponExample);
        for (MarketCoupon marketCoupon : marketCoupons) {//拿到优惠券信息
            criteria1.andCouponIdEqualTo(marketCoupon.getId());
            long affectRows = marketCouponUserMapper.countByExample(marketCouponUserExample);
            if (affectRows == 0) {//说明用户没有该优惠券，可以执行兑换。

                MarketCouponUser marketCouponUser = new MarketCouponUser();
                marketCouponUser.setUserId(userId);
                marketCouponUser.setStatus((short) 0);
                marketCouponUser.setStartTime(marketCoupon.getStartTime());
                marketCouponUser.setEndTime(marketCoupon.getEndTime());
                marketCouponUser.setAddTime(new Date());
                marketCouponUser.setUpdateTime(new Date());
                marketCouponUser.setCouponId(marketCoupon.getId());
                marketCouponUser.setDeleted(marketCoupon.getDeleted());
                row = marketCouponUserMapper.insertSelective(marketCouponUser);
            } else return -1;
        }
        if (row != -1) return 1;
        return -1;
    }

    @Autowired
    MarketCartMapper marketCartMapper;

    @Override
    public WxCouponSelectListVo seletlist(Integer cartId, Integer userId) {
        //endTime 大于 使用时间
        //根据金额显示满足使用的优惠券
        //根据userId拿到用户所有优惠券id,再去优惠券表中拿最低使用价有多少。
        //使用完后status为1；
        //过期status为2；

        //更新过期的couponUser
        if (userId == null) {
            return null;
        }
        updateCouponUserExpired(userId);

        ArrayList<WxCouponSelectListVo.ListBean> listBeans = new ArrayList<>();
        WxCouponSelectListVo wxCouponSelectListVo = new WxCouponSelectListVo();

        MarketCart marketCart = marketCartMapper.selectByPrimaryKey(cartId);//拿价格

        MarketCouponUserExample marketCouponUserExample = new MarketCouponUserExample();
        MarketCouponUserExample.Criteria criteria = marketCouponUserExample.createCriteria();
        criteria.andStatusEqualTo((short) 0);//未使用的优惠券
        criteria.andUserIdEqualTo(userId);//拿到用户用户所有优惠券
        criteria.andEndTimeGreaterThanOrEqualTo(new Date());//使用时间小于结束时间。
        List<MarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(marketCouponUserExample);

        for (MarketCouponUser marketCouponUser : marketCouponUsers) {
            WxCouponSelectListVo.ListBean listBean = new WxCouponSelectListVo.ListBean();
            MarketCouponExample marketCouponExample = new MarketCouponExample();//筛选优惠券
            MarketCouponExample.Criteria criteria2 = marketCouponExample.createCriteria();
            criteria2.andIdEqualTo(marketCouponUser.getCouponId());
            criteria2.andMinLessThanOrEqualTo(marketCart.getPrice());//筛选了价格符合条件，
            List<MarketCoupon> marketCoupons = marketCouponMapper.selectByExample(marketCouponExample);

            for (MarketCoupon marketCoupon : marketCoupons) {
                listBean.setAvailable(true);
                listBean.setCid(marketCoupon.getId());
                listBean.setDesc(marketCoupon.getDesc());
                listBean.setDiscount(marketCoupon.getDiscount());
                listBean.setEndTime(marketCoupon.getEndTime());
                listBean.setId(marketCouponUser.getId());
                listBean.setMin(marketCoupon.getMin());
                listBean.setName(marketCoupon.getName());
                listBean.setStartTime(marketCoupon.getStartTime());
                listBean.setTag(marketCoupon.getTag());
                listBeans.add(listBean);
            }
        }
        wxCouponSelectListVo.setLimit(listBeans.size());
        wxCouponSelectListVo.setPage(1);
        wxCouponSelectListVo.setPages(1);
        wxCouponSelectListVo.setTotal(listBeans.size());
        wxCouponSelectListVo.setList(listBeans);


        return wxCouponSelectListVo;
    }
}
